package com.home.fansea.config;

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.util.ThreadContext;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Autowired
    MyRealm myRealm;

    /**
     * shiro过滤器配置
     *
     * @param securityManager 安全管理器
     * @return Shiro过滤器
     */
    @Bean("securityManager")
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        ThreadContext.bind(securityManager);//加上这句代码手动绑定
        /*//创建密码加密对象
        HashedCredentialsMatcher matcher=new HashedCredentialsMatcher();
        //设置加密对象的属性
        matcher.setHashAlgorithmName("md5");
        matcher.setHashIterations(3);
        //将加密对象  存储到Realm对象中
        myRealm.setCredentialsMatcher(matcher);*/
        // 配置Realm等组件
        myRealm.setName("myRealm");
        securityManager.setRealm(myRealm);
        return securityManager;
    }

    //配置shiro的拦截范围，我们的登录接口肯定是需要放行的
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") SecurityManager securityManager) {
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(securityManager);

        /*
        anon 无需验证就能够访问
        authc 必须任认证了才能够访问
        user： 必须认证且拥有记住我才能够访问
        perms 拥有某个资源权限才能够访问
        role 拥有某个角色的权限才能够访问
         */
        // 定义过滤器链
        Map<String, String> filterChainDefinitionMap = new HashMap<>();

        // 配置匿名访问的URL
        filterChainDefinitionMap.put("/user/login", "anon");
        filterChainDefinitionMap.put("/static/**", "anon"); // 允许匿名访问静态资源
        filterChainDefinitionMap.put("/swagger-ui.html", "anon");
        filterChainDefinitionMap.put("/swagger/**", "anon");

        // 需要认证的URL
//        filterChainDefinitionMap.put("/**/**", "authc"); // 除了上述匿名路径，其余都需要认证
        filterChainDefinitionMap.put("/**", "authc"); // 除了上述匿名路径，其余都需要认证

        factoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
//        factoryBean.setLoginUrl("/user/login");
        return factoryBean;
    }


}